import { useState, useRef, useEffect } from "react";
import { message, Card, Button, Row, Col, Popconfirm } from "antd";
import useCommonTable from "@/hooks/useCommonTable";
import { DownloadOutlined } from "@ant-design/icons";
import "./index.less";
import {
  getInfo,
  getYlCurve,
  getScCurve,
  getLhCurve,
  add,
  exportPore,
  addPore,
  updatePore,
  removePore,
} from "@/services/pore";
import { history } from "umi";
import ProForm, {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-form";
import { type2Options, typeLHOptions, typeSCOptions } from "@/const";
import { downLoadFile } from "@/utils";
import CharData from "./components/CharData";

export default ({ action = true }) => {
  const { query } = history.location;
  const { id, type = "yl" } = query;
  const formRef1 = useRef();
  const [visible, setVisible] = useState(false);
  const [showModal1, setShowModal1] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [fitting, setFitting] = useState("");

  const [list, setList] = useState([]);
  const [currentId, setCurrentId] = useState("");
  const [dataSource, setDataSource] = useState([]);
  const formRef = useRef();

  const fetchInfo = async () => {
    const res = await getInfo({ poreDataId: id, type });
    if (res.data) {
      setList(res.data);
      const curId = res.data?.[0]?.id;
      setCurrentId(curId);
    }
  };

  useEffect(() => {
    if (id && type) {
      fetchInfo();
    }
  }, [id, type]);

  const columnsMap = {
    yl: [
      {
        title: "样品名称",
        dataIndex: "name",
      },
      {
        title: "样品厚度 mm",
        dataIndex: "thickness",
      },
      {
        title: "σ0.4/MPa",
        dataIndex: "a04",
      },
      {
        title: "重量g",
        dataIndex: "weight",
        sorter: {
          compare: (a, b) => a.weight - b.weight,
          multiple: 3,
        },
      },
      {
        title: "密度g/cm3",
        dataIndex: "density",
      },
      {
        title: "平均孔径 μm",
        dataIndex: "averageAperture",
      },
      {
        title: "平均圆度",
        dataIndex: "averageRoundness",
      },
      {
        title: "平均面积",
        dataIndex: "averageArea",
      },
      {
        title: "等面积圆直径 μm",
        dataIndex: "areaDiameter",
      },
      {
        title: "泡体直径",
        dataIndex: "bubbleDiameter",
      },
    ],
    SC: [
      {
        title: "样品名称",
        dataIndex: "name",
      },
      {
        title: "样品厚度 mm",
        dataIndex: "thickness",
      },
      {
        title: "压缩应变40%载荷N",
        dataIndex: "strain40SourceLoad",
      },
      {
        title: "10min载荷N",
        dataIndex: "sourceLoad10",
      },
      {
        title: "191min载荷N",
        dataIndex: "sourceLoad191",
      },
      {
        title: "10min松弛率",
        dataIndex: "t10RelaxationRate",
      },

      {
        title: "t0松弛率",
        dataIndex: "t0RelaxationRate",
      },

      {
        title: "重量g",
        dataIndex: "weight",
      },
      {
        title: "密度g/cm3",
        dataIndex: "density",
      },
      {
        title: "平均孔径 μm",
        dataIndex: "averageAperture",
      },
      {
        title: "平均圆度",
        dataIndex: "averageRoundness",
      },
      {
        title: "平均面积",
        dataIndex: "averageArea",
      },
      {
        title: "等面积圆直径 μm",
        dataIndex: "areaDiameter",
      },
      {
        title: "泡体直径",
        dataIndex: "bubbleDiameter",
      },
    ],
    LH: [
      {
        title: "应力",
        dataIndex: "yl",
      },
      {
        title: "温度",
        dataIndex: "temperature",
      },
      {
        title: "编号",
        dataIndex: "name",
      },
      {
        title: "样品厚度 mm",
        dataIndex: "thickness2105",
      },
      {
        title: "重量g",
        dataIndex: "weight",
      },
      {
        title: "密度g/cm3",
        dataIndex: "density",
      },
      {
        title: "σ0.4/MPa",
        dataIndex: "a042105",
      },
      {
        title: "样品厚度 mm",
        dataIndex: "thickness2310",
      },
      {
        title: "永久变形",
        dataIndex: "permanentDeformation",
      },
      {
        title: "σ0.4/MPa",
        dataIndex: "a042310",
      },
      {
        title: "松弛率%",
        dataIndex: "relaxationRate",
      },
      {
        title: "压缩应变在预设点 (载荷 2 N)",
        dataIndex: "strainPresetPoint",
      },
      {
        title: "平均孔径 μm",
        dataIndex: "averageAperture",
      },
      {
        title: "平均圆度",
        dataIndex: "averageRoundness",
      },
      {
        title: "平均面积",
        dataIndex: "averageArea",
      },
      {
        title: "等面积圆直径 μm",
        dataIndex: "areaDiameter",
      },
      {
        title: "泡体直径",
        dataIndex: "bubbleDiameter",
      },
    ],
  };

  const defaultCofig = {
    xField: "x",
    yField: "y",
    colorField: "series",
    seriesField: "series",
    pointSize: 5,
    shape: "circle",
    // 线
    // regressionLine: {
    //   type: "poly", // linear, exp, loess, log, poly, pow, quad
    // },
    legend: {
      position: "top",
    },
    xAxis: {
      title: {
        text: "总老化时间/D）",
        style: {
          fontSize: 14,
        },
      },
    },
    yAxis: {
      title: {
        text: "松弛率/%",
        style: {
          fontSize: 14,
        },
      },
    },
    meta: {
      x: {
        alias: "总老化时间/D）",
      },
      y: {
        alias: "松弛率/%",
        min: 0, // x轴最小值
        max: 100, // x轴最大值
        // tickInterval: 10, // x轴步长
      },
      series: {
        alias: "类型",
      },
    },
  };

  const renderFormItem = () => {
    const doms = {
      yl: (
        <>
          <ProFormText
            label="样品名称"
            name="name"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="样品厚度 mm"
            name="thickness"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="σ0.4/MPa"
            name="a04"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="重量g"
            name="weight"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="密度g/cm3"
            name="density"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均孔径 μm"
            name="averageAperture"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均圆度"
            name="averageRoundness"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均面积"
            name="averageArea"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="等面积圆直径 μm"
            name="areaDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="泡体直径"
            name="bubbleDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
        </>
      ),
      SC: (
        <>
          <ProFormText
            label="样品名称"
            name="name"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="样品厚度 mm"
            name="thickness"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="压缩应变40%载荷N"
            name="strain40SourceLoad"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="10min载荷N"
            name="sourceLoad10"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="191min载荷N"
            name="sourceLoad191"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="10min松弛率"
            name="t10RelaxationRate"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="t0松弛率"
            name="t0RelaxationRate"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="重量g"
            name="weight"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="密度g/cm3"
            name="density"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="平均孔径 μm"
            name="averageAperture"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均圆度"
            name="averageRoundness"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均面积"
            name="averageArea"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="等面积圆直径 μm"
            name="areaDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="泡体直径"
            name="bubbleDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
        </>
      ),
      LH: (
        <>
          <ProFormText
            label="应力"
            name="yl"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="温度"
            name="temperature"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="编号"
            name="name"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="样品厚度 mm"
            name="thickness2105"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="重量g"
            name="weight"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="密度g/cm3"
            name="density"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="σ0.4/MPa"
            name="a042105"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="样品厚度 mm"
            name="thickness2310"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="永久变形"
            name="permanentDeformation"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="σ0.4/MPa"
            name="a042310"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="松弛率%"
            name="relaxationRate"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="压缩应变在预设点 (载荷 2 N)"
            name="strainPresetPoint"
            rules={[{ required: true, message: "请输入" }]}
          />

          <ProFormText
            label="平均孔径 μm"
            name="averageAperture"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均圆度"
            name="averageRoundness"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="平均面积"
            name="averageArea"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="等面积圆直径 μm"
            name="areaDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
          <ProFormText
            label="泡体直径"
            name="bubbleDiameter"
            rules={[{ required: true, message: "请输入" }]}
          />
        </>
      ),
    };
    return doms[type];
  };

  return (
    <div className="test-container">
      <div className="list-left">
        <div>
          <div className="my-table-title">样品名称</div>
          <div className="list-left-items">
            {list?.map((item) => (
              <div
                key={item.id}
                onClick={() => {
                  if (item.id === currentId) {
                    return;
                  }
                  setCurrentId(item.id);
                }}
                className={`item ${item.id === currentId ? "active" : ""}`}
              >
                {item.name}
              </div>
            ))}
          </div>
        </div>

        {/* <div className="upload-btn">{renderForm()}</div> */}
      </div>

      <Card style={{ marginLeft: 20, flex: 1 }}>
        {useCommonTable({
          dataSource: list,
          title: "数据",
          columns: columnsMap[type],
          actionColumnWidth: 160,
          modalWidth: 800,
          renderFormItem,
          renderAdd: null,
          search: false,
          onlyAction: true,
          showCheckbox: false,
          pagination: false,
          add,
          onFinish: async (values, actionRef, record, actionType) => {
            let func = updatePore;
            if (actionType == 1) {
              func = addPore;
            }
            const res = await func({
              ...values,
              id: record?.id,
              type,
              poreDataId: id,
            });
            if (res.data) {
              fetchInfo();
              return true;
            }
          },
          // remove: removePore,
          renderOtherAction: (_, record, actionRef) => {
            return (
              <Popconfirm
                key="remove"
                title="确定删除?"
                onConfirm={async () => {
                  const res = await removePore({ id: record.id, type });
                  if (res.data) {
                    message.success("删除成功");
                    fetchInfo();
                  }
                }}
              >
                <Button
                  style={{ marginLeft: 10 }}
                  className="my-delete-btn"
                  type="text"
                >
                  删除
                </Button>
              </Popconfirm>
            );
          },
          scroll: {
            x: 1000,
          },
          renderAddOther: (actionRef) => {
            return action ? (
              <>
                <Button
                  icon={<DownloadOutlined />}
                  onClick={async () => {
                    const blob = await exportPore({ poreDataId: id, type });
                    downLoadFile(blob, Date.now() + ".xlsx");
                  }}
                >
                  导出
                </Button>
                <Button
                  onClick={async () => {
                    setShowModal1(true);
                  }}
                >
                  查看曲线
                </Button>
              </>
            ) : null;
          },
        })}
      </Card>

      <ModalForm
        formRef={formRef1}
        width={"90%"}
        style={{ height: 600, overflowY: "auto" }}
        visible={showModal1}
        title={"曲线"}
        onVisibleChange={(bool) => {
          setDataList([]);
          setShowModal1(bool);
        }}
        modalProps={{
          destroyOnClose: true,
        }}
        layout="vertical"
        submitter={{
          render: () => {},
        }}
      >
        <Row>
          <Col span={12}>
            <ProFormSelect
              label="查看数据"
              name="types"
              allowClear
              fieldProps={{
                mode: "multiple",
                options:
                  type == "LH"
                    ? typeLHOptions
                    : type == "SC"
                    ? typeSCOptions
                    : type2Options,
              }}
              rules={[{ required: true, message: "请选择" }]}
            />
          </Col>
          <Col>
            <Button
              style={{ marginTop: 30, marginLeft: 20 }}
              type="primary"
              onClick={async () => {
                setDataList([]);
                const data = await formRef1.current?.validateFields();
                const funcs = {
                  yl: getYlCurve,
                  SC: getScCurve,
                  LH: getLhCurve,
                };
                const res = await funcs[type]({
                  id: id,
                  types: data.types,
                });
                setFitting(res.data?.fitting);
                setDataList(res.data?.poreCurves);
              }}
            >
              确定
            </Button>
          </Col>
        </Row>

        <div
          style={{ fontSize: 20, margin: 20 }}
          dangerouslySetInnerHTML={{ __html: fitting }}
        ></div>

        <div style={{ display: "flex" }}>
          {dataList.map((res) => {
            const maxArr = res.sourceList?.map((item) => item.y * 1);
            const max = Math.max(...maxArr) * 1.5;
            return (
              <>
                <div style={{ flex: 1 }}>
                  <CharData value={res} type={type} />
                  <div
                    style={{ textAlign: "center", marginTop: 20 }}
                    dangerouslySetInnerHTML={{
                      __html: res.formula.replace("\n", "<br />"),
                    }}
                  ></div>
                </div>
              </>
            );
          })}
        </div>
      </ModalForm>
    </div>
  );
};
